package com.archstoday.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.common.AsRes;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.DictEntity;
import com.archstoday.entity.UpdateEntity;
import com.archstoday.fragment.HomeFragment;
import com.archstoday.fragment.LikeListFragment;
import com.archstoday.fragment.UserFragment;
import com.archstoday.utils.PdfURLUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.utils.WechatUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.StringUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 首页
 */
public class MainActivity extends AsBaseActivity {

    private TextView mHomeBtn, mLikeBtn, mUserBtn;

    private int mIndex;
    private HomeFragment mHomeFragment;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_main);
        mHomeBtn = (TextView) findViewById(R.id.main_tab_home);
        mLikeBtn = (TextView) findViewById(R.id.main_tab_like);
        mUserBtn = (TextView) findViewById(R.id.main_tab_user);
    }

    @Override
    protected void initData(Bundle bundle) {
        WechatUtils.regToWx(mContext);
        upDate();
        getDict();
        checkTab(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mIndex == 0) {
                mHomeFragment.onBack();
            } else {
                onBack();
            }
        }
        return false;
    }

    public void onBack() {
        AlertDialog dialog = new AlertDialog.Builder(mContext)
                .setMessage("确定要退出今日建闻吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        appFinish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create();
        dialog.show();
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.main_tab_home);
        setOnClickListener(R.id.main_tab_like);
        setOnClickListener(R.id.main_tab_user);
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.main_tab_home:
                checkTab(0);
                break;
            case R.id.main_tab_like:
                checkTab(1);
                break;
            case R.id.main_tab_user:
                checkTab(2);
                break;
        }
    }

    private void checkTab(int position) {
        mIndex = position;
        Map<String, String> info;
        switch (position) {
            case 0:
                info = new HashMap<>();
                info.put("name", "mainpage");
                getEvent(BaseApp.E_MAIN, BaseApp.PAGE_MAIN,
                        ToolUtils.mapToJson(info));

                mHomeBtn.setSelected(true);
                mLikeBtn.setSelected(false);
                mUserBtn.setSelected(false);

                mHomeFragment = new HomeFragment();
                replaceContent(R.id.main_layout, mHomeFragment);
                break;
            case 1:
                info = new HashMap<>();
                info.put("name", "myfav");
                getEvent(BaseApp.E_MAIN, BaseApp.PAGE_MAIN,
                        ToolUtils.mapToJson(info));


                mHomeBtn.setSelected(false);
                mLikeBtn.setSelected(true);
                mUserBtn.setSelected(false);

                replaceContent(R.id.main_layout, new LikeListFragment());
                break;
            case 2:
                info = new HashMap<>();
                info.put("name", "usercenter");
                getEvent(BaseApp.E_MAIN, BaseApp.PAGE_MAIN,
                        ToolUtils.mapToJson(info));


                mHomeBtn.setSelected(false);
                mLikeBtn.setSelected(false);
                mUserBtn.setSelected(true);

                replaceContent(R.id.main_layout, new UserFragment());
                break;
        }
    }

    private void upDate() {
        String version = getVersion();

        initParameter();
        mParams.put("app_id", mApp.getDeviceID(mContext));
        mParams.put("version_id", version.substring(0, version.lastIndexOf(".")));
        mParams.put("version_mini", Integer.valueOf(version.substring(version.lastIndexOf(".") + 1)));
        mParams.put("type", "android");
        mParams.put("channel", mApp.mChannel);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_UPDATE),
                AsRes.GET_UPDATE, mParams, UpdateEntity.class);
    }

    private void getDict() {
        initParameter();
        mParams.put("type", "oss_file_link");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.DICT_GET),
                AsRes.DICT_GET, mParams, DictEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_UPDATE) {
            final UpdateEntity entity = (UpdateEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (entity.getData() == null
                        || StringUtil.isEmpty(entity.getData().getApkUrl())) {
//                    showToast(R.string.update_toast);
                } else {
                    if (entity.getData().getIsForced() == 1) {
                        AlertDialog dialog = new AlertDialog.Builder(mContext)
                                .setTitle(R.string.update_title)
                                .setMessage(entity.getData().getUpgradePoint())
                                .setNegativeButton(R.string.cancel_btn, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                })
                                .setPositiveButton(R.string.submit_btn, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        if (ToolUtils.isPermission(mContext)) {
                                            ToolUtils.intoDownloadManager(mContext,
                                                    entity.getData().getApkUrl(), false);
                                        } else {
                                            ToolUtils.getAppDetailSettingIntent(mContext);
                                        }
                                    }
                                })
                                .create();
                        dialog.show();
                    } else if (entity.getData().getIsForced() == 2) {
                        AlertDialog dialog = new AlertDialog.Builder(mContext)
                                .setTitle(R.string.update_title)
                                .setMessage(entity.getData().getUpgradePoint())
                                .setPositiveButton(R.string.submit_btn, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        if (ToolUtils.isPermission(mContext)) {
                                            showToast(R.string.download_toast);
                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    ToolUtils.intoDownloadManager(mContext,
                                                            entity.getData().getApkUrl(), true);
                                                }

                                            }, 150);
                                        } else {
                                            ToolUtils.getAppDetailSettingIntent(mContext);
                                        }
                                    }
                                })
                                .create();
                        dialog.setCancelable(false);
                        dialog.show();
                    }
                }
            }
        } else if (client.getUrlIdentifier() == AsRes.DICT_GET) {
            DictEntity entity = (DictEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (entity.getData() != null && entity.getData().size() > 0) {
                    PdfURLUtils.getInstance().setPdf_url(
                            entity.getData().get(0).getValue());
                }
            }
        }
    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {

    }
}
